package com.itheima.controller.store;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.store.Catalog;
import com.itheima.domain.store.Company;
import com.itheima.domain.store.Question;
import com.itheima.service.store.QuestionService;
import com.itheima.service.store.impl.QuestionServiceImpl;
import com.itheima.utils.BeanUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 部门 控制层
 */
@WebServlet("/store/question/*")
public class QuestionServlet extends BaseServlet {

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取分页属性
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");
        //System.out.println(pageNum);
        //获取列表
        Page<Question> page = questionService.findAll(pageNum, pageSize);
        //配置分页信息
        PageInfo<Question> pageInfo = new PageInfo<Question>(page);
        //存入请求域
        req.setAttribute("page", pageInfo);
        //跳转页面
        req.getRequestDispatcher("/pages/store/question/list.jsp").forward(req, resp);
    }


    //文件上传测试
    private void testUpload(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //确认该操作是否支持文件上传操作, enctype="multipart/form-data"
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //Servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //从request中获取数据
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            for (FileItem fileItem : fileItems) {
                //判断当前表单是否是文件表单
                if (!fileItem.isFormField()) {
                    //从临时目录写到指定位置
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"), fileItem.getName()));
                }
            }
        }
    }

    //进入添加数据页面 回显信息 需要返回列表
    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取企业信息
        List<Company> companyList = companyService.findAll();
        //获取类别信息
        List<Catalog> catalogList = catalogService.findAll();
        //设置到请求域
        req.setAttribute("companyList", companyList);
        req.setAttribute("catalogList", catalogList);
        //跳转页面
        req.getRequestDispatcher("/pages/store/question/add.jsp").forward(req, resp);
    }

    //保存信息
    private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        //判断是否支持上传文件操作
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //创建servlet上传文件核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(req);

            //标记位 有文件上传时为true
            boolean flag = false;
            for (FileItem fileItem : fileItems) {
                if (StringUtils.isNotBlank(fileItem.getName())) {
                    flag = true;
                    break;
                }
            }

            //封装数据
            Question question = BeanUtil.fillBean(fileItems, Question.class);
            //System.out.println(question);
            //调用业务层进行保存
            String questionId = questionService.save(question,flag);
            //将上传的文件保存到服务端
            for (FileItem fileItem : fileItems) {
                //非表单判断 不是表单就是文件
                if(!fileItem.isFormField()){
                    //写出
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"),questionId));
                }
            }
        }

        //跳转到list
        list(req,resp);
    }

    //删除多条记录
    private void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String ids = req.getParameter("ids");
        System.out.println(ids);
        //删除
        boolean isDel = questionService.deleteByIds(ids);
        //删除成功了就把图片一起删除
        String[] split = ids.split(",");
        for (String filename : split) {
            new File(this.getServletContext().getRealPath("upload"),filename).delete();
        }
        //System.out.println("============="+isDel);
        //响应
        resp.getWriter().write(mapper.writeValueAsString(isDel));
    }

    //通过id找到对象并打开编辑页面
    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Question question = questionService.findById(id);
        System.out.println(question);
        //获取企业信息
        List<Company> companyList = companyService.findAll();
        //获取类别信息
        List<Catalog> catalogList = catalogService.findAll();
        //设置到请求域
        req.setAttribute("companyList", companyList);
        req.setAttribute("catalogList", catalogList);
        //设置到请求域
        req.setAttribute("question", question);
        //跳转到编辑页面
        req.getRequestDispatcher("/pages/store/question/update.jsp").forward(req, resp);
    }


    //通过id修改
    private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //判断是否支持文件上传操作
        if(ServletFileUpload.isMultipartContent(req)){
            //创建磁盘文件工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //创建Servlet核心文件上传对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //从request读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            //获取图片名称
            String picture = req.getParameter("picture");

            for (FileItem fileItem : fileItems) {
                //判断非表单数据
                if(!fileItem.isFormField()){
                    //判断非空
                    if(StringUtils.isNotBlank(fileItem.getName())){
                        fileItem.write(new File(this.getServletContext().getRealPath("upload"),picture));
                    }
                }
            }

            //封装用户信息
            Question question = BeanUtil.fillBean(req, Question.class);
            //更新信息
            questionService.updateQuestion(question);
        }

        //刷新页面
        list(req, resp);
    }
}
